/**
 * 数据库服务 - 处理远程数据库连接和表结构读取
 * 现在支持真实API调用和模拟数据
 */
import { DatabaseApiService } from "./databaseApiService"

export interface DatabaseConnection {
  type: "mysql" | "postgresql" | "oracle"
  host: string
  port: number
  database: string
  username: string
  password: string
  charset?: string
  connectTimeout?: number
  useSSL?: boolean
  allowPublicKeyRetrieval?: boolean
  tableFilter?: string
}

export interface DatabaseField {
  name: string
  type: string
  length?: number
  precision?: number
  scale?: number
  nullable: boolean
  primaryKey: boolean
  autoIncrement: boolean
  defaultValue?: string
  comment?: string
}

export interface DatabaseTable {
  name: string
  comment?: string
  fields: DatabaseField[]
  indexes?: DatabaseIndex[]
}

export interface DatabaseIndex {
  name: string
  fields: string[]
  unique: boolean
  type: "PRIMARY" | "UNIQUE" | "INDEX" | "FULLTEXT"
}

export interface DatabaseSchema {
  tables: DatabaseTable[]
  version?: string
  charset?: string
}

export class DatabaseService {
  /**
   * 测试数据库连接
   */
  static async testConnection(config: DatabaseConnection, useMock: boolean = false): Promise<boolean> {
    try {
      if (!useMock) {
        // 调用真实API
        const response = await DatabaseApiService.testConnection(config)
        return response.data.success
      }

      // 模拟连接测试
      await new Promise(resolve => setTimeout(resolve, 1500))

      // 模拟连接失败的情况
      if (config.host === "fail") {
        throw new Error("连接超时")
      }

      return true
    } catch (error) {
      console.error("数据库连接测试失败:", error)
      throw error
    }
  }

  /**
   * 获取数据库所有表
   */
  static async getTables(config: DatabaseConnection, tableFilter?: string, useMock: boolean = false): Promise<string[]> {
    try {
      if (!useMock) {
        // 调用真实API
        const response = await DatabaseApiService.getTables(config, tableFilter)
        return response.data
      }

      // 模拟获取表列表
      await new Promise(resolve => setTimeout(resolve, 1000))

      const allTables = [
        "users",
        "orders",
        "products",
        "categories",
        "order_items",
        "companies",
        "departments",
        "employees",
        "sys_config",
        "sys_logs",
        "user_roles",
        "permissions",
        "role_permissions"
      ]

      // 应用表过滤器
      if (tableFilter) {
        const filters = tableFilter.split(",").map(f => f.trim()).filter(f => f)
        return allTables.filter(table =>
          filters.some(filter => table.startsWith(filter))
        )
      }

      return allTables
    } catch (error) {
      console.error("获取表列表失败:", error)
      throw error
    }
  }

  /**
   * 获取表结构
   */
  static async getTableStructure(config: DatabaseConnection, tableName: string, useMock: boolean = false): Promise<DatabaseTable> {
    try {
      if (!useMock) {
        // 调用真实API
        const response = await DatabaseApiService.getTableDetail(config, tableName)
        return response.data
      }

      // 模拟获取表结构
      await new Promise(resolve => setTimeout(resolve, 500))

      return this.getMockTableStructure(tableName)
    } catch (error) {
      console.error(`获取表 ${tableName} 结构失败:`, error)
      throw error
    }
  }

  /**
   * 批量获取表结构
   */
  static async getTablesStructure(config: DatabaseConnection, tableNames: string[]): Promise<DatabaseTable[]> {
    try {
      const _tables: DatabaseTable[] = []

      // 并发获取所有表结构
      const promises = tableNames.map(tableName => this.getTableStructure(config, tableName))
      const results = await Promise.all(promises)

      return results
    } catch (error) {
      console.error("批量获取表结构失败:", error)
      throw error
    }
  }

  /**
   * 获取完整数据库结构
   */
  static async getDatabaseSchema(config: DatabaseConnection, tableFilter?: string): Promise<DatabaseSchema> {
    try {
      // 1. 获取所有表名
      const tableNames = await this.getTables(config, tableFilter)

      // 2. 获取所有表结构
      const tables = await this.getTablesStructure(config, tableNames)

      return {
        tables,
        version: "8.0.32", // MySQL版本
        charset: config.charset || "utf8mb4"
      }
    } catch (error) {
      console.error("获取数据库结构失败:", error)
      throw error
    }
  }

  /**
   * 模拟表结构数据（用于开发测试）
   */
  private static getMockTableStructure(tableName: string): DatabaseTable {
    const mockTables: Record<string, DatabaseTable> = {
      users: {
        name: "users",
        comment: "用户表",
        fields: [
          { name: "id", type: "bigint", nullable: false, primaryKey: true, autoIncrement: true, comment: "主键ID" },
          { name: "username", type: "varchar", length: 50, nullable: false, primaryKey: false, autoIncrement: false, comment: "用户名" },
          { name: "email", type: "varchar", length: 100, nullable: false, primaryKey: false, autoIncrement: false, comment: "邮箱地址" },
          { name: "password", type: "varchar", length: 255, nullable: false, primaryKey: false, autoIncrement: false, comment: "密码哈希" },
          { name: "phone", type: "varchar", length: 20, nullable: true, primaryKey: false, autoIncrement: false, comment: "手机号码" },
          { name: "avatar", type: "varchar", length: 500, nullable: true, primaryKey: false, autoIncrement: false, comment: "头像URL" },
          { name: "status", type: "tinyint", nullable: false, primaryKey: false, autoIncrement: false, defaultValue: "1", comment: "状态：1-正常，0-禁用" },
          { name: "last_login_at", type: "datetime", nullable: true, primaryKey: false, autoIncrement: false, comment: "最后登录时间" },
          { name: "created_at", type: "datetime", nullable: false, primaryKey: false, autoIncrement: false, comment: "创建时间" },
          { name: "updated_at", type: "datetime", nullable: false, primaryKey: false, autoIncrement: false, comment: "更新时间" }
        ]
      },
      orders: {
        name: "orders",
        comment: "订单表",
        fields: [
          { name: "id", type: "bigint", nullable: false, primaryKey: true, autoIncrement: true, comment: "订单ID" },
          { name: "user_id", type: "bigint", nullable: false, primaryKey: false, autoIncrement: false, comment: "用户ID" },
          { name: "order_no", type: "varchar", length: 32, nullable: false, primaryKey: false, autoIncrement: false, comment: "订单号" },
          { name: "total_amount", type: "decimal", precision: 10, scale: 2, nullable: false, primaryKey: false, autoIncrement: false, comment: "订单总金额" },
          { name: "discount_amount", type: "decimal", precision: 10, scale: 2, nullable: false, primaryKey: false, autoIncrement: false, defaultValue: "0.00", comment: "优惠金额" },
          { name: "paid_amount", type: "decimal", precision: 10, scale: 2, nullable: false, primaryKey: false, autoIncrement: false, defaultValue: "0.00", comment: "已支付金额" },
          { name: "status", type: "tinyint", nullable: false, primaryKey: false, autoIncrement: false, defaultValue: "1", comment: "订单状态：1-待支付，2-已支付，3-已发货，4-已完成，5-已取消" },
          { name: "remark", type: "text", nullable: true, primaryKey: false, autoIncrement: false, comment: "订单备注" },
          { name: "created_at", type: "datetime", nullable: false, primaryKey: false, autoIncrement: false, comment: "创建时间" },
          { name: "updated_at", type: "datetime", nullable: false, primaryKey: false, autoIncrement: false, comment: "更新时间" }
        ]
      },
      products: {
        name: "products",
        comment: "商品表",
        fields: [
          { name: "id", type: "bigint", nullable: false, primaryKey: true, autoIncrement: true, comment: "商品ID" },
          { name: "category_id", type: "bigint", nullable: false, primaryKey: false, autoIncrement: false, comment: "分类ID" },
          { name: "name", type: "varchar", length: 200, nullable: false, primaryKey: false, autoIncrement: false, comment: "商品名称" },
          { name: "description", type: "text", nullable: true, primaryKey: false, autoIncrement: false, comment: "商品描述" },
          { name: "price", type: "decimal", precision: 10, scale: 2, nullable: false, primaryKey: false, autoIncrement: false, comment: "商品价格" },
          { name: "stock", type: "int", nullable: false, primaryKey: false, autoIncrement: false, defaultValue: "0", comment: "库存数量" },
          { name: "images", type: "json", nullable: true, primaryKey: false, autoIncrement: false, comment: "商品图片JSON数组" },
          { name: "status", type: "tinyint", nullable: false, primaryKey: false, autoIncrement: false, defaultValue: "1", comment: "商品状态：1-上架，0-下架" },
          { name: "created_at", type: "datetime", nullable: false, primaryKey: false, autoIncrement: false, comment: "创建时间" },
          { name: "updated_at", type: "datetime", nullable: false, primaryKey: false, autoIncrement: false, comment: "更新时间" }
        ]
      },
      companies: {
        name: "companies",
        comment: "公司表",
        fields: [
          { name: "id", type: "bigint", nullable: false, primaryKey: true, autoIncrement: true, comment: "公司ID" },
          { name: "name", type: "varchar", length: 200, nullable: false, primaryKey: false, autoIncrement: false, comment: "公司名称" },
          { name: "code", type: "varchar", length: 50, nullable: false, primaryKey: false, autoIncrement: false, comment: "公司编码" },
          { name: "address", type: "varchar", length: 500, nullable: true, primaryKey: false, autoIncrement: false, comment: "公司地址" },
          { name: "contact_person", type: "varchar", length: 100, nullable: true, primaryKey: false, autoIncrement: false, comment: "联系人" },
          { name: "contact_phone", type: "varchar", length: 20, nullable: true, primaryKey: false, autoIncrement: false, comment: "联系电话" },
          { name: "established_date", type: "date", nullable: true, primaryKey: false, autoIncrement: false, comment: "成立日期" },
          { name: "status", type: "tinyint", nullable: false, primaryKey: false, autoIncrement: false, defaultValue: "1", comment: "状态：1-正常，0-停用" },
          { name: "created_at", type: "datetime", nullable: false, primaryKey: false, autoIncrement: false, comment: "创建时间" },
          { name: "updated_at", type: "datetime", nullable: false, primaryKey: false, autoIncrement: false, comment: "更新时间" }
        ]
      }
    }

    return mockTables[tableName] || {
      name: tableName,
      comment: `${tableName}表`,
      fields: [
        { name: "id", type: "bigint", nullable: false, primaryKey: true, autoIncrement: true, comment: "主键ID" },
        { name: "name", type: "varchar", length: 100, nullable: false, primaryKey: false, autoIncrement: false, comment: "名称" },
        { name: "created_at", type: "datetime", nullable: false, primaryKey: false, autoIncrement: false, comment: "创建时间" },
        { name: "updated_at", type: "datetime", nullable: false, primaryKey: false, autoIncrement: false, comment: "更新时间" }
      ]
    }
  }

  /**
   * 将数据库字段类型转换为Java类型
   */
  static convertToJavaType(dbType: string): string {
    const typeMap: Record<string, string> = {
      tinyint: "Integer",
      smallint: "Integer",
      mediumint: "Integer",
      int: "Integer",
      integer: "Integer",
      bigint: "Long",
      decimal: "BigDecimal",
      numeric: "BigDecimal",
      float: "Float",
      double: "Double",
      real: "Double",
      bit: "Boolean",
      boolean: "Boolean",
      char: "String",
      varchar: "String",
      text: "String",
      mediumtext: "String",
      longtext: "String",
      date: "LocalDate",
      time: "LocalTime",
      datetime: "LocalDateTime",
      timestamp: "LocalDateTime",
      year: "Integer",
      binary: "byte[]",
      varbinary: "byte[]",
      blob: "byte[]",
      mediumblob: "byte[]",
      longblob: "byte[]",
      json: "String"
    }

    return typeMap[dbType.toLowerCase()] || "String"
  }

  /**
   * 将数据库字段类型转换为TypeScript类型
   */
  static convertToTypeScriptType(dbType: string): string {
    const typeMap: Record<string, string> = {
      tinyint: "number",
      smallint: "number",
      mediumint: "number",
      int: "number",
      integer: "number",
      bigint: "number",
      decimal: "number",
      numeric: "number",
      float: "number",
      double: "number",
      real: "number",
      bit: "boolean",
      boolean: "boolean",
      char: "string",
      varchar: "string",
      text: "string",
      mediumtext: "string",
      longtext: "string",
      date: "string",
      time: "string",
      datetime: "string",
      timestamp: "string",
      year: "number",
      binary: "string",
      varbinary: "string",
      blob: "string",
      mediumblob: "string",
      longblob: "string",
      json: "any"
    }

    return typeMap[dbType.toLowerCase()] || "string"
  }
}
